﻿/*
Copyright (c) 2011 <a href="http://www.gutgames.com">James Craig</a>

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.*/

#region Usings

using System;
using System.IO;
using System.Net;
using System.Text;
using System.Text.RegularExpressions;
using System.Web;
using System.Web.Caching;
using Utilities.DataTypes;
using Utilities.Events.EventArgs;
using OptimizerPrime.BaseClasses;
using Utilities.Web.ExtensionMethods;

#endregion

namespace OptimizerPrime.HttpHandlers
{
    /// <summary>
    /// Handler for transmitting javascript files
    /// </summary>
    public class JavaScriptHandler : BaseHandler
    {
        #region Public Functions

        /// <summary>
        /// Process the request
        /// </summary>
        /// <param name="context">current context</param>
        public override void ProcessRequest(HttpContext context)
        {
            if (string.IsNullOrEmpty(context.Request.QueryString["Script"]))
                return;
            if (!OnStart(new OnStartEventArgs()))
                return;

            string path = context.Request.QueryString["Script"];
            string script = null;

            if (Utils.Generic.SetHeaders(path, context, "text/javascript"))
            {
                if (!string.IsNullOrEmpty(path))
                    script = RetrieveLocalScripts(path);

                if (!string.IsNullOrEmpty(script))
                {
                    context.Response.Write(script);
                    context.HTTPCompress();
                }
            }
            OnEnd(new OnEndEventArgs());
        }

        /// <summary>
        /// This item is not reusable
        /// </summary>
        public override bool IsReusable
        {
            get { return false; }
        }

        #endregion

        #region Private Functions

        /// <summary>
        /// Gets local scripts and minifies them
        /// </summary>
        /// <param name="File">List of files to load</param>
        /// <returns>A string containing the script files</returns>
        private static string RetrieveLocalScripts(string File)
        {
            string[] Splitter = { "," };
            string[] Files = File.Split(Splitter, StringSplitOptions.RemoveEmptyEntries);
            StringBuilder Builder = new StringBuilder();

            foreach (string FileUsing in Files)
            {
                string CurrentFile = HttpContext.Current.Server.MapPath(FileUsing);
                if (!CurrentFile.EndsWith(".js", StringComparison.OrdinalIgnoreCase))
                    throw new System.Security.SecurityException("No access");

                Tuple<string, DateTime> result = (Tuple<string, DateTime>)HttpContext.Current.Cache[CurrentFile];

                if (result == null)
                {
                    using (StreamReader reader = new StreamReader(CurrentFile))
                    {
                        result = new Tuple<string, DateTime>(reader.ReadToEnd().Minify(MinificationType.JavaScript), System.IO.File.GetLastWriteTime(CurrentFile));
                        HttpContext.Current.Cache.Insert(CurrentFile, result, new CacheDependency(CurrentFile));
                    }
                }
                Builder.Append(result.Item1);
            }
            return Builder.ToString();
        }

        #endregion
    }
}